package com.ex.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ex.model.TTeacher;
import com.ex.service.TeacherService;
import com.ex.util.Pagination;
import com.ex.util.ParentRecordFront;

@Controller
@RequestMapping(value = "/teacher/")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class TeacherController {
	@Autowired
	private TeacherService teacherservice;

	// 老师登录入口
	@RequestMapping(value = "login")
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request, HttpSession session) {
		// 创建返回给前端的结果集
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 通过request得到页面属性
		String name = request.getParameter("userName");
		String psd = request.getParameter("password");

		if ("".equals(name) || "".equals(psd)) {
			return null;
		}

		// 创建一个对象，通过设置对象的属性来查询是否存在这个用户
		TTeacher teacher = new TTeacher();
		teacher.setName(name);
		teacher.setPassword(psd);

		List<TTeacher> resultTeacher = teacherservice.queryTeacher(teacher);

		if (resultTeacher.size() == 1) {
			session.setAttribute("teacher", resultTeacher.get(0));
			resultMap.put("errorcode", 0);
		} else {
			resultMap.put("errorcode", 1);
			resultMap.put("errormessage", "用户名或密码不存在");
		}
		return resultMap;

	}

	// 登录后基本信息的入口
	@RequestMapping(value = "info")
	@ResponseBody
	public Map<String, Object> info(HttpSession session) {
		// 创建返回给前端的结果集
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 得到当前登录的用户信息
		TTeacher tTeacher = (TTeacher) session.getAttribute("teacher");

		// 查询当前用户的班级
		String info = (String) teacherservice.queryClass(tTeacher);

		String tclassName = "";
		if (!"".equals(info)) {
			tclassName = info;
		}

		resultMap.put("teachername", tTeacher.getName());
		resultMap.put("teacherclass", tclassName);

		return resultMap;

	}

	public Pagination findStuInfosByRecord(HttpSession session,
			ParentRecordFront prf) {
		System.out.println(prf);
		TTeacher tTeacher = (TTeacher) session.getAttribute("loginUser");
		Pagination pagination = teacherservice.queryRecordsByTeacher(tTeacher,
				prf);
//		if (pagination == null) {
//			pagination = new Pagination(0, "", null);
//		}
		return pagination;
	}

}
